<template>
  <view class="content">
    <view class="banner">
      <view class="bannerImgView" @click="linkMiniProgramUrl(this.appId_ft, this.url_zmybm)">
        <image class="bannerImg" mode="aspectFit" src="../../static/zmy.png"></image>
        <text>周末游报名</text>
      </view>
      <view class="bannerImgView" @click="linkMiniProgramUrl(this.appId_ft, this.url_jchtj)">
        <image class="bannerImg" mode="aspectFit" src="../../static/phb.png">
        </image>
        <text>聚餐好推荐</text>
      </view>
      <view class="bannerImgView" @click="linkMiniProgramUrl(this.appId_ft, this.url_dystd)">
        <image class="bannerImg" mode="aspectFit" src="../../static/jqxd.png">
        </image>
        <text>第一手探店</text>
      </view>
    </view>

    <map id="map" class="map" :latitude="latitude" :longitude="longitude" show-location=true :markers="markers"
      @markertap="markerTap" @labeltap="markerTap">
      <cover-image class="img-map2" src="../../static/icon-location.png" @click="positioned"></cover-image>
    </map>
    <view class="scroll-Y" :style="{'height': items.length>=3? '300px' : ''}">
      <list>
        <cell v-for="item in items" :key="item.id">
          <view class="scroll-view-item" @click="scrollClick(item)">
            <text user-select=true>{{item.name}}</text>
            <p>{{item.content}}</p>
          </view>
        </cell>
      </list>
      <view v-if="this.items.length === 1" class="bottomBottom">
        <view style="width: 65vw;margin-left: 30rpx;border-radius: 1ch;">
          <p style="font-size: 30rpx; color: gray">爬取有精度损失，记得仔细看看 :)</p>
        </view>

        <button size="mini" type="primary" @click="navBtnClick">去这里</button>
      </view>

    </view>
    <view class="bottom">
      <!-- <uni-link href="https://www.navo.top/wx_msgs/spview/4703525/3897331" text="我要推荐" copyTips="跳转未实现,敬请期待"></uni-link> -->
      <text style="color: slategray; text-decoration: underline; font-size: 30rpx"
        @click="linkOthers(this.url_recommend)">我要推荐</text>
      <view class="search-bar">
        <uni-search-bar v-model="keyword" @confirm="search" @input="search" @focus="focus">
        </uni-search-bar>
      </view>
    </view>
  </view>
</template>

<script>
  import items from '../../static/data.json'

  export default {
    data() {
      return {
        id: 0, // 使用 marker点击事件 需要填写id
        title: 'map',
        latitude: 20.050747409393274,
        longitude: 110.34770539665573,
        markers: [],
        // tapped_item: {
        //   name: "",
        //   content: ""
        // },
        scrollTop: 0,
        keyword: "",
        items: [],
        mapCtx: undefined,
        appId_ft: 'wx55423a2f8005eb86',
        url_recommend: "https://mp.weixin.qq.com/s?__biz=MjM5MTM5ODY4NA==&mid=2651778920&idx=1&sn=a9f0caa904b1d8602178cbf42ff542c2&chksm=bd4c611b8a3be80d08eabe673519d70517e0767657c3a94f0abc9169cc65e0996905e1112c02#rd",
        url_zmybm: 'pages/common/blank-page/index?weappSharePath=pages%2Fhome%2Ffeature%2Findex%3Falias%3DhvYaIS5AMn%26kdt_id%3D2018036',
        url_jchtj: 'pages/home/dashboard/index',
        url_dystd: 'pages/common/blank-page/index?weappSharePath=pages%2Fhome%2Ffeature%2Findex%3Falias%3DAYlGSQe2xV%26kdt_id%3D2018036'
      }
    },
    onLoad() {
      this.updateCheck()
      this.getloc();
      this.loadJson();
      uni.showShareMenu({
        withShareTicket: true
      });
      this.mapCtx = uni.createMapContext("map", this)
    },
    methods: {
      getloc() {
        let that = this;
        uni.authorize({
          scope: "scope.userLocation",
          success: () => {
            uni.getLocation({
              type: 'gcj02',
              success: function(res) {
                console.log('实时获取用户坐标:', res, new Date());
                that.latitude = res.latitude;
                that.longitude = res.longitude;
              },
              fail: function(err) {
                console.error(err)
              }
            });
          },
          fail: () => reject("请授权获取你的位置，否则部分功能将无法使用！"),
        });
      },
      loadJson() {
        // console.log(items)
        let i = 0;
        for (let item of items) {
          let marker_item = {
            id: i,
            name: item.name,
            joinCluster: true,
            label: {
              content: item.name,
              color: '#ffffff',
              bgColor: '#009F9A79',
              fontSize: 15
            },
            latitude: item.lat,
            longitude: item.lng,
            height: 30,
            width: 20,
            content: item.comment,
            shared_url: item.shared_url,
            // iconPath: '../../static/marker_red.png'
          };
          marker_item.label.anchorX = -(marker_item.name.length * 15) / 2; // 文字居中，因为text_align真机调试无效
          this.markers.push(marker_item);
          i++;
        }
        console.log(i);
        console.log(this.markers.length);
      },

      markerTap(e) {
        // this.tapped_item = this.markers[e.markerId];
        this.items = [this.markers[e.markerId]];
        // this.tapped_id = e.markerId
        // console.log(e.markerId)
      },

      toNavigation(loc) {
        uni.navigateToMiniProgram({
          appId: 'wx7643d5f831302ab0',
          path: "pages/multiScheme/multiScheme?endLoc=" + JSON.stringify(loc),
          success(res) {
            // 打开成功
            console.log(res)
          }
        })
      },

      // 定位
      positioned() {
        this.mapCtx.moveToLocation({ //moveToLocation将地图中心移动到当前定位点，需要配合map组件的show-location使用
          latitude: this.latitude,
          longitude: this.longitude
        });
      },

      linkOthers(url) {
        uni.navigateTo({
          // 此处的链接为小程序上面新建的webview页面路径，参数url为要跳转外链的地址
          url: "/pages/wv/wv?url=" + encodeURIComponent(url)
        });
      },

      linkMiniProgramUrl(appId, path) {
        uni.navigateToMiniProgram({
          appId: appId,
          path: path,
          success(res) {
            console.log(res)
          }
        })
      },

      // 滚动列表的元素点击
      scrollClick(item) {
        console.log(item)
        this.items = [item]
        // this.latitude = item.latitude
        // this.longitude = item.longitude
        this.mapCtx.moveToLocation({ //moveToLocation将地图中心移动到当前定位点，需要配合map组件的show-location使用
          latitude: item.latitude,
          longitude: item.longitude
        });
        // this.mapCtx.includePoints({
        //   points: [{
        //     latitude: item.latitude,
        //     longitude: item.longitude
        //   }, {
        //     latitude: this.latitude,
        //     longitude: this.longitude
        //   }]
        // });
      },

      navBtnClick() {
        if (this.items.length === 0) {
          console.log("no items");
          return;
        }
        let item = this.items[0];
        console.log(item)
        let loc = {
          name: item.name,
          location: {
            lat: item.latitude,
            lng: item.longitude
          }
        };
        this.toNavigation(loc);
      },

      // 搜索并定位
      search(e) {
        let keyword = e.value ? e.value : e;
        console.log(keyword);
        if (keyword.length === 0) {
          this.items = []
          return;
        }
        let reg = new RegExp(keyword);
        let arr = [];
        for (var i = 0; i < this.markers.length; i++) {
          if (reg.test(this.markers[i].name) || reg.test(this.markers[i].content)) {
            arr.push(this.markers[i]);
          }
        }
        this.items = arr;
      },

      focus() {
        this.search(this.keyword);
      },

      updateCheck() {
        const updateManager = uni.getUpdateManager();

        updateManager.onCheckForUpdate(function(res) {
          // 请求完新版本信息的回调
          console.log(res.hasUpdate);
        });

        updateManager.onUpdateReady(function(res) {
          uni.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate();
              }
            }
          });

        });

        updateManager.onUpdateFailed(function(res) {
          // 新的版本下载失败
          uni.showModal({
            title: '下载失败',
            content: '请检查网络，稍后重试',
          });
        });
      }
    }
  }
</script>

<style>
  .banner {
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
    align-items: baseline;
  }

  .bannerImgView {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 25rpx;
    margin: 20rpx 0 20rpx 0;
  }

  .bannerImg {
    width: 30vw;
    height: 8vh;
    margin-bottom: 5px;
  }


  /*  .notice {
    height: 12vh;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-evenly;
  } */

  /*  .left {
    background-color: indianred;
    padding: 5px;
    width: 65vw;
    margin: 5px;
    border-radius: 1ch;
  }

  .right {
    width: 30vw;
    margin: 5px;
    padding: 5px;
    text-align: center;
    border: 1px solid green;
    border-radius: 1ch;
  } */

  .map {
    width: 100%;
    height: 78vh;
  }

  .img-map2 {
    width: 65rpx;
    height: 65rpx;
    position: fixed;
    bottom: 30vh;
    right: 2vh;
    background-color: #FFFFFF;
    border-radius: 5px;
    box-shadow: 0px 0px 6px hsl(0deg 0% 0% / 0.3);
  }

  .search-bar {
    /* background-color: aquamarine; */
    width: 75vw;
    /* margin-top: 63vh; */
    /* position: fixed; */
  }

  .bottom {
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
    align-items: baseline;
    height: 10vh;
  }

  .bottomBottom {
    display: flex;
    flex-direction: row;
    justify-content: space-evenly;
    align-items: baseline;
  }

  .scroll-Y {
    position: fixed;
    bottom: 9vh;
    width: 100vw;
    background-color: white;
    opacity: 0.9;
    overflow-y: auto;
    border-radius: 2ch 2ch 0 0;
  }

  .scroll-view-item {
    margin-left: 20px;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    /* text-align: center; */
    font-size: 36rpx;
  }
</style>
